<!--
  * lmabbe
  *
  * @Author:    lmabbe
  * @Date:      2025-06-26 19:25:24
  * @Copyright  lmabbe
-->
<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.workOrderId ? '编辑' : '添加'"
    :width="850"
    @cancel="onClose"
  >
    <a-form ref="formRef" :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }" :model="form" :rules="rules">
      <a-input v-model:value="form.workOrderId" hidden placeholder="工单ID" style="width: 100%" />
      <a-row>
        <a-col :span="12">
          <a-form-item label="工单编号" name="workOrderCode">
            <a-input v-model:value="form.workOrderCode" placeholder="工单编号" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="客户编号" name="customerCode">
            <a-select
              v-model:value="form.customerCode"
              :allowClear="true"
              :style="`width: 100%`"
              placeholder="请选择归属客户"
              @change="
                (value) => {
                  form.customerAbbreviation = customerAllData.find((item) => item.customerCode === value).customerAbbreviation;
                }
              "
            >
              <a-select-option v-for="item in customerAllData" :key="item.customerCode" :value="item.customerCode">
                {{ item.customerAbbreviation }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料编码" name="materialCode">
            <TableSelect
              v-model:modelValue="form.materialCode"
              :columns="[
                { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
                { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
                { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
                { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
              ]"
              :options="materialData"
              :placeholder="'输入物料编号/名称/规格'"
              @search="handleMaterialSearch"
              @select="handleMaterialSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="BOM版本" name="bomVer">
            <a-input v-model:value="form.bomVer" placeholder="Bom版本" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="生产数量" name="productionQty">
            <a-input-number v-model:value="form.productionQty" :min="1" placeholder="生产数量" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="单价" name="unitPrice">
            <a-input-number v-model:value="form.unitPrice" :min="0" placeholder="单价" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="下单日期" name="orderTime">
            <a-date-picker v-model:value="form.orderTime" placeholder="下单日期" show-time style="width: 100%" valueFormat="YYYY-MM-DD HH:mm:ss" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="交货日期" name="deliveryDate">
            <a-date-picker v-model:value="form.deliveryDate" placeholder="交货日期" show-time style="width: 100%" valueFormat="YYYY-MM-DD HH:mm:ss" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="客户订单号" name="customerOrderCode">
            <a-input v-model:value="form.customerOrderCode" placeholder="客户订单号" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="按发料条码上料" name="controlBarcodeFlag">
            <BooleanSelect v-model:value="form.controlBarcodeFlag" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { workOrderInfoApi } from '/@/api/business/product/order/work-order-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import BooleanSelect from '/@/components/framework/boolean-select/index.vue';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import TableSelect from '/@/components/TableSelect/index.vue';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    customerAll();
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    workOrderId: undefined, //工单ID
    workOrderCode: undefined, //工单编号
    customerCode: undefined, //客户编号
    customerAbbreviation: undefined, //客户简称
    materialCode: undefined, //物料编码
    bomVer: undefined,
    materialName: undefined, //物料名称
    materialSpec: undefined, //物料规格
    materialDesc: undefined, //物料描述
    unitPrice: undefined, //单价
    productionQty: undefined, //生产数量
    customerOrderCode: undefined, //客户订单号
    orderTime: undefined, //下单日期
    deliveryDate: undefined, //交货日期
    orderStatus: undefined, //订单状态：[1.等待齐料 2.等待排产 3.备料中 4.生产中 5.生产完成 6.等待交付 7.已交付 8.关闭]
    remark: undefined, //备注
    controlBarcodeFlag: undefined, //是否按发料条码上料
  };

  let form = reactive({ ...formDefault });

  const rules = {
    workOrderId: [{ required: true, message: '工单ID 必填' }],
    workOrderCode: [{ required: true, message: '工单编号 必填' }],
    bomVer: [{ required: true, message: 'BOM版本 必填' }],
    customerCode: [{ required: true, message: '客户编号 必填' }],
    materialCode: [{ required: true, message: '物料编码 必填' }],
    productionQty: [{ required: true, message: '生产数量 必填' }],
    orderTime: [{ required: true, message: '下单日期 必填' }],
    deliveryDate: [{ required: true, message: '交货日期 必填' }],
    controlBarcodeFlag: [{ required: true, message: '是否按发料条码上料 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (form.workOrderId) {
        await workOrderInfoApi.update(form);
      } else {
        await workOrderInfoApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  const customerAllData = ref();

  function customerAll() {
    customerInfoApi.customerAll().then((res) => {
      customerAllData.value = res.data;
    });
  }

  const materialData = ref();
  const handleMaterialSearch = (searchValue) => {
    let param = {
      keywords: searchValue,
      belongCustomer: form.customerCode,
      materialProperty: 'PRODUCT',
    };
    materialInfoApi.searchTop10(param).then((res) => {
      materialData.value = res.data;
    });
  };

  const handleMaterialSelect = (value) => {
    form.materialCode = value.record.materialCode;
    form.materialDesc = value.record.materialDesc;
    form.materialName = value.record.materialName;
    form.materialSpec = value.record.materialSpec;
  };

  defineExpose({
    show,
  });
</script>
